package com.boarsoft.boar.sys.biz;

import java.util.List;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boarsoft.boar.sys.SysUserRoleBiz;
import com.boarsoft.boar.sys.entity.SysRole;
import com.boarsoft.boar.sys.entity.UserRole;
import com.boarsoft.common.Util;
import com.boarsoft.common.dao.PagedResult;
import com.boarsoft.hibernate.biz.SimpleBizImpl;

@Component("sysUserRoleBiz")
public class SysUserRoleBizImpl extends SimpleBizImpl implements SysUserRoleBiz {

	@Override
	@Transactional(readOnly = true)
	public PagedResult<SysRole> list(String uid, String key, String orderBy, int pageNo, int pageSize) {
		StringBuffer sb = new StringBuffer();
		sb.append(" from SysRole r join r.users u where u.id='");
		sb.append(uid).append("' and r.status=").append(SysRole.STATUS_INUSE);
		if (Util.strIsNotEmpty(key)) {
			sb.append(" and (r.name like '%").append(key);
			sb.append("%')");
		}
		int total = Util.object2int(dao.getValue("select count(r.id)".concat(sb.toString())), 0);
		sb.append(" order by r.name");
		log.info(sb.toString());
		List<SysRole> lt = dao.list("select r".concat(sb.toString()), pageNo, pageSize);
		return new PagedResult<SysRole>(total, lt, pageNo, pageSize);
	}

	@Override
	@Transactional
	public boolean toggle(String uid, String rid, String corpId, String deptId) {
		String w = String.format("and userId='%s' and roleId='%s' and corpId='%s' and deptId='%s'", uid, rid, corpId,deptId);
		UserRole o = (UserRole) dao.find(UserRole.class, w);
		if (o == null) {
			o = new UserRole();
			o.setUserId(uid);
			o.setRoleId(rid);
			o.setCorpId(corpId);
			o.setDeptId(deptId);
			dao.save(o);
			return true;
		} else {
			dao.delete(o);
			return false;
		}
	}

	@Override
	@Transactional
	public void add(String uid, String rId, String corpId, String deptId) {
		String w = String.format("and userId='%s' and roleId='%s' and corpId='%s' and deptId='%s'", uid, rId,corpId,deptId);
		UserRole o = (UserRole) dao.find(UserRole.class, w);
		if (o == null) {
			o = new UserRole();
			o.setUserId(uid);
			o.setRoleId(rId);
			o.setCorpId(corpId);
			o.setDeptId(deptId);
			dao.save(o);
		}
	}

	@Override
	@Transactional(readOnly = true)
	public String find(String roleCode, String deptId) {
		String w = String.format("and code='%s' and deptId='%s'", roleCode, deptId);
		SysRole role = (SysRole) dao.find(SysRole.class, w);
		if (role != null) {
			return role.getId();
		} else {
			return null;
		}
	}
}